from django.shortcuts import render

from .filters import UserProfileFilter
from .models import UserProfile, Post
from rest_framework import viewsets
from rest_framework.request import Request
from rest_framework import status
from loguru import logger
from op_drf.pagination import Pagination
from op_drf.response import SuccessResponse
from op_drf.viewsets import CustomModelViewSet
from op_drf.dj_utils import set_delete
from op_drf.filters import DataLevelPermissionsFilter
from vadmin.serializers import ReadUserProfileSerializer, WriteUserProfileSerializer, ReadPostSerializer, \
    CreatePostSerializer, UpdatePostSerializer


# Create your views here.


class UserProfileViewSet(CustomModelViewSet):
    # 数据
    queryset = UserProfile.objects.all()
    if hasattr(UserProfile, "is_delete"):
        queryset = queryset.filter(is_delete=False)

    # 显示序列化
    serializer_class = ReadUserProfileSerializer
    # 创建序列化
    create_serializer_class = WriteUserProfileSerializer
    # 更新序列化
    update_serializer_class = WriteUserProfileSerializer
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_class = UserProfileFilter
    # 权限，根据用户设置访问权限
    extra_filter_backends = [DataLevelPermissionsFilter]

    # update_extra_permission_classes = (CommonPermission,)
    # destroy_extra_permission_classes = (CommonPermission,)
    # create_extra_permission_classes = (CommonPermission,)
    # 搜索字段
    # search_fields = ("asset_code",)
    # 默认排序
    # ordering = ["-create_time"]

    def destroy(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("前端携带的数据： %s" % kwargs)

        instance = self.get_object_list()
        # instance = self.get_object()
        logger.debug(instance)
        if hasattr(self, "handle_logging"):
            self.handle_logging(request, instance=instance, *args, **kwargs)
        self.perform_destroy(instance)
        return SuccessResponse(status=status.HTTP_204_NO_CONTENT)

    def perform_destroy(self, instance):
        # instance.delete()
        # 不再执行物理删除，执行逻辑删除
        set_delete(instance)


class PostViewSet(CustomModelViewSet):
    # 数据
    queryset = Post.objects.all()
    if hasattr(Post, "is_delete"):
        queryset = queryset.filter(is_delete=False)

    # 显示序列化
    serializer_class = ReadPostSerializer
    # 创建序列化
    create_serializer_class = CreatePostSerializer
    # 更新序列化
    update_serializer_class = UpdatePostSerializer
    # 分页
    pagination_class = Pagination